package com.cts.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cts.annotation.OperationLogger;
import com.cts.entity.Blog;
import com.cts.entity.BlogTag;
import com.cts.model.dto.BlogListDTO;
import com.cts.model.vo.*;
import com.cts.service.BlogService;
import com.cts.service.BlogTagService;
import com.cts.util.DictUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @projectName: CBlog
 * @package: com.cts.controller.admin
 * @className: BlogAdminController
 * @author: chentongsheng
 * @description: TODO
 * @date: 2023/2/23 13:44
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class BlogAdminController {

    @Autowired
    BlogService blogService;

    @Autowired
    BlogTagService blogTagService;

    @Autowired
    DictUtils dictUtils;

    @OperationLogger("获取博客信息")
    @ApiOperation("获取博客信息")
    @RequestMapping("/getBlogById")
    public Result getBlogById(@RequestParam Long id){
        if(Objects.isNull(id)){
            return Result.error("请求失败");
        }
        Blog blog = blogService.getById(id);

        // 获取字典值
        Map<Long, String> cateGoryDict = dictUtils.getCateGoryDict();
        log.info("分类码值转换开始...");
        blog.setCategoryName(cateGoryDict.get(blog.getCategoryId()));
        log.info("文章{}的分类码值为{}：{}", blog.getTitle(), blog.getCategoryId(), blog.getCategoryName());
        log.info("分类码值转换结束...");

        // 查询Tag
        Long[] tagList = blogTagService.getTagList(id);
        blog.setTagList(tagList);

        return Result.ok("请求成功", blog);
    }

    @OperationLogger("获取博客列表")
    @ApiOperation("获取博客列表")
    @PostMapping("/getBlogList")
    public Result getBlogList(@RequestBody BlogListDTO blogListDTO){
        PageResultVO<Blog> pageResultVO = blogService.getBlogList(blogListDTO);
        return Result.ok("请求成功", pageResultVO);
    }

    @OperationLogger("删除博客")
    @ApiOperation("删除博客")
    @PostMapping("/deleteBlogById")
    public Result deleteBlogById(@RequestParam Long id){
        Boolean flag = blogService.removeById(id);
        if(!flag){
            return Result.error("删除失败");
        }
        flag = blogTagService.removeTags(id);
        if(!flag){
            return Result.error("删除失败");
        }
        return Result.ok("删除成功");
    }

    @OperationLogger("发布博客")
    @ApiOperation("发布博客")
    @PostMapping("/publishBlog")
    public Result publishBlog(@RequestParam Integer id, Boolean isPublished){
        Boolean flag = blogService.publishBlog(id, isPublished);
        if(flag){
            return Result.ok("更新成功");
        }
        return Result.error("更新失败");
    }

    @OperationLogger("置顶博客")
    @ApiOperation("置顶博客")
    @PostMapping("/topBlog")
    public Result topBlog(@RequestParam Integer id, Boolean isTop){
        Boolean flag = blogService.topBlog(id, isTop);
        if(flag){
            return Result.ok("更新成功");
        }
        return Result.error("更新失败");
    }

    @OperationLogger("保存博客")
    @ApiOperation("保存博客")
    @PostMapping("/saveBlog")
    public Result saveBlog(@RequestBody Blog blog){
        // 判断是否为空
        if(Objects.isNull(blog.getTitle()) || Objects.isNull(blog.getFirstPicture())) {
            return Result.error("标题或首页图片不能为空");
        }
        // 检查并设置默认值
        Blog newBlog = blogService.setBlogDefault(blog);
        // 保存博客
        boolean save = blogService.saveOrUpdate(newBlog);

        if(save) {
            Long blogId = newBlog.getId();
            // 保存标签
            Long[] tagList = newBlog.getTagList();
            ArrayList<BlogTag> blogTags = new ArrayList<>();
            for (Long tag : tagList) {
                BlogTag blogTag = new BlogTag();
                blogTag.setBlogId(blogId);
                blogTag.setTagId(tag);
                blogTags.add(blogTag);
            }
            LambdaQueryWrapper<BlogTag> blogTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
            blogTagLambdaQueryWrapper.eq(BlogTag::getBlogId, blogId);
            // 先删除旧的标签，再保存新的标签
            blogTagService.remove(blogTagLambdaQueryWrapper);
            log.info("删除旧标签,id: {}", blogId);
            blogTagService.saveBatch(blogTags);
            log.info("保存新标签,id: {}", blogId);
        }

        return Result.ok("保存成功");
    }

    @OperationLogger("更新可见性")
    @ApiOperation("更新可见性")
    @PostMapping("/updateBlogVisibility")
    public Result updateBlogVisibility(@RequestBody Blog blog){
        switch (blog.getVisibleModel()){
            case "private" :
                blogService.privateVisible(blog.getId());
                break;
            case "protect" :
            case "public" :
                blogService.updateVisible(blog);
                break;
            default:
                log.info("更新可见性成功");
        }
        return Result.ok("请求成功");
    }

}
